/**
 * 日期范围选择，带至今选项
 */
import React from 'react';
import { Checkbox, DatePicker } from 'antd';

const RangePicker = React.forwardRef((props, ref) => {
    const { value = [], onChange } = props;
    const [startValue, endValue] = value;
    const [endOpen, setEndOpen] = React.useState();

    const disabledStartDate = _startValue => {
        if (!_startValue || !endValue) {
            return false;
        }
        return _startValue.valueOf() > endValue.valueOf();
    };

    const disabledEndDate = _endValue => {
        if (!_endValue || !startValue) {
            return false;
        }
        return _endValue.valueOf() <= startValue.valueOf();
    };

    const handleChange = field => _value => {
        const final = {};
        final[field] = _value;
        onChange([final.start || startValue, final.end || endValue]);
    };

    const handleStartOpenChange = open => {
        if (!open) {
            setEndOpen(true);
        }
    };

    const handleEndOpenChange = open => {
        setEndOpen(open);
    };

    const handleCheckboxChange = e => {
        if (e.target.checked) {
            onChange([startValue, '']);
        }
    };

    return (
        <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }} ref={ref}>
            <DatePicker
                style={{ flex: 1 }}
                disabledDate={disabledStartDate}
                format="YYYY-MM-DD"
                value={startValue}
                placeholder="开始时间"
                onChange={handleChange('start')}
                onOpenChange={handleStartOpenChange}
            />
            <div style={{ width: 8 }} />
            <DatePicker
                style={{ flex: 1 }}
                disabledDate={disabledEndDate}
                format="YYYY-MM-DD"
                value={endValue}
                placeholder="结束时间"
                onChange={handleChange('end')}
                open={endOpen}
                onOpenChange={handleEndOpenChange}
            />
            <Checkbox
                style={{ position: 'absolute', right: '-68px' }}
                checked={!endValue}
                onChange={handleCheckboxChange}
            >
                至今
            </Checkbox>
        </div>
    );
});

export default RangePicker;
